package com.auto.reg.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

public final class FakeLoginUtil {

    public static String doPostForSessionId(String reqUrl, Map<String, String> parameters) {
        HttpURLConnection urlConn = null;
        String sessionid;
        try {
            urlConn = sendPost(reqUrl, parameters);
            sessionid = getJSessionId(urlConn);
            // String responseContent = getContent(urlConn);
            return sessionid;
        } finally {
            if (urlConn != null) {
                urlConn.disconnect();
                urlConn = null;
            }
        }
    }
    
    public static String doPostForContent(String reqUrl, Map<String, String> parameters, String cookie) {
        HttpURLConnection urlConn = null;
        try {
            urlConn = sendPostWithCookie(reqUrl, parameters, cookie);
            String responseContent = getContent(urlConn);
            return responseContent.trim();
        } finally {
            if (urlConn != null) {
                urlConn.disconnect();
                urlConn = null;
            }
        }
    }

    private static String getContent(HttpURLConnection urlConn) {
        try {
            String responseContent = null;
            InputStream in = urlConn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
            return responseContent;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    
    private static String getJSessionId(HttpURLConnection urlConn) {
    	String sessionid = "";
    	InputStream in = null;
    	try {
			in = urlConn.getInputStream();
		    sessionid = urlConn.getHeaderField("Set-cookie");
		} catch (Exception e) {
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	return sessionid;
    }

    public static byte[] getBytes(String reqUrl, Map<String, String> parameters) {
        HttpURLConnection conn = sendPost(reqUrl, parameters);
        return getBytes(conn);
    }
    
    private static byte[] getBytes(HttpURLConnection urlConn) {
        try {
            InputStream in = urlConn.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int i = 0; (i = in.read(buf)) > 0;)
                os.write(buf, 0, i);
            in.close();
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static HttpURLConnection sendPost(String reqUrl, Map<String, String> parameters) {
        HttpURLConnection urlConn = null;
        try {
            String params = generatorParamString(parameters);
            URL url = new URL(reqUrl);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            
            urlConn
             .setRequestProperty(
             "User-Agent",
             "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");

            urlConn
             .setRequestProperty("Connection", "Keep-Alive");
            
            urlConn.setRequestProperty("Host", "id.apple.com");
            urlConn.setConnectTimeout(5000);
            urlConn.setReadTimeout(5000);
            urlConn.setDoOutput(true);
            byte[] b = params.getBytes();
            urlConn.getOutputStream().write(b, 0, b.length);
            urlConn.getOutputStream().flush();
            urlConn.getOutputStream().close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return urlConn;
    }
    
    public static HttpURLConnection sendPostWithCookie(String reqUrl, Map<String, String> parameters, String cookie) {
        HttpURLConnection urlConn = null;
        try {
            String params = generatorParamString(parameters);
            URL url = new URL(reqUrl);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setRequestProperty("Cookie", cookie);
            
            urlConn.setConnectTimeout(5000);
            urlConn.setReadTimeout(5000);
            urlConn.setDoOutput(true);
            byte[] b = params.getBytes();
            urlConn.getOutputStream().write(b, 0, b.length);
            urlConn.getOutputStream().flush();
            urlConn.getOutputStream().close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return urlConn;
    }

    public static String sendGet(String url , String param) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection urlConn = null;
        try
        {
        	URL realUrl = new URL(url);
        	urlConn = (HttpURLConnection) realUrl.openConnection();
            urlConn.connect(); 
		    in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
		    String line;
		    while ((line = in.readLine())!= null)
		    {
		    	result += line;
		    }
		} catch(Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
		    try {
			    if (in != null) {
			    	in.close();
			    }
		    } catch (IOException ex) {
		    	ex.printStackTrace();
		    }
		}
        return result;
    }

    public static String generatorParamString(Map<String, String> parameters) {
        StringBuffer params = new StringBuffer();
        if (parameters != null) {
            for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String value = parameters.get(name);
                params.append(name + "=");
                try {
                    params.append(URLEncoder.encode(value, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e.getMessage(), e);
                } catch (Exception e) {
                    String message = String.format("'%s'='%s'", name, value);
                    throw new RuntimeException(message, e);
                }
                if (iter.hasNext()) params.append("&");
            }
        }
        return params.toString();
    }

    /**
     * 
     * @param link
     * @param charset
     * @return
     */
    public static String doGet(String link, String charset) {
        try {
            URL url = new URL(link);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int i = 0; (i = in.read(buf)) > 0;) {
                out.write(buf, 0, i);
            }
            out.flush();
            String s = new String(out.toByteArray(), charset);
            return s;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static String doGet(String link) {
        return doGet(link, "UTF-8");
    }

    public static int getIntResponse(String link) {
        String str = doGet(link);
        return Integer.parseInt(str.trim());
    }
}
